import Vue from 'vue'
import VueRouter from 'vue-router'
import Cookies from "js-cookie";
import Layout from "@/views/Layout.vue";

Vue.use(VueRouter)

const routes = [
  // ==== 登录 ====
  {
    path: '/login',
    name: 'Login',
    component: ()=> import('@/views/login/Login'),
  },
// ==== 主页 ====
  {
    //将该部分专门定义为Layout
    path: '/',
    name: 'Layout',
    component: Layout,
    //通过redirect重定向layout和home:通过各种方法将各种网络请求重新定个方向转到其它位置,此处将layout的请求转移到home中
    redirect: 'home',
    children: [
    //    在children内部定义子路由
      { path: 'home', name: 'Home', component: () => import('@/views/home/HomeView')},
      //====  User  ====
      { path: 'userList', name: 'UserList', component: () => import('@/views/user/User'),},
      { path: 'addUser', name: 'AddUser', component: () => import('@/views/user/AddUser'),},
      { path: 'editUser', name: 'EditUser', component: () => import('@/views/user/EditUser'),},

      //====  Admin  ====
      { path: 'adminList', name: 'AdminList', component: () => import('@/views/admin/List.vue'),},
      { path: 'addAdmin', name: 'AddAdmin', component: () => import('@/views/admin/Add.vue'),},
      { path: 'editAdmin', name: 'EditAdmin', component: () => import('@/views/admin/Edit.vue'),},


      //====  Category  ====
      { path: 'categoryList', name: 'CategoryList', component: () => import('@/views/category/List.vue'),},
      { path: 'addCategory', name: 'AddCategory', component: () => import('@/views/category/Add.vue'),},
      { path: 'editCategory', name: 'EditCategory', component: () => import('@/views/category/Edit.vue'),},

      //====  Book  ====
      { path: 'bookList', name: 'BookList', component: () => import('@/views/book/List.vue'),},
      { path: 'addBook', name: 'AddBook', component: () => import('@/views/book/Add.vue'),},
      { path: 'editBook', name: 'EditBook', component: () => import('@/views/book/Edit.vue'),}
    ]

  },
  //  当"主页"中所有页面都没有,提示404
  {
    path:'*',
    component:() => import('@/views/404')
  }

]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
//路由守卫,如果当前路径不是login,强制跳转到login
router.beforeEach((to,from,next)  => {
  if(to.path === '/login') next()
  const admin = Cookies.get("admin")
  if(!admin && to.path !== '/login')
    return next("/login")
  //访问 /home的时候,且cookie里存放数据,此时直接放行
  next()
})
export default router
